package com.yunwaikeji.gy_tool_library.utils.permission;

import android.content.Context;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.yunwaikeji.gy_tool_library.utils.GYUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GYPermissionUtils {
    public static GYPermissionBuilder newBuilder() {
        return new GYPermissionBuilder();
    }

    private int requestCode;

    private final List<String> permissionList = new ArrayList<>();
    private PermissionResult permissionResult;

    public GYPermissionUtils addPermissions(List<String> permissionList) {
        this.permissionList.addAll(permissionList);
        return this;
    }

    public GYPermissionUtils addPermissions(String... permissions) {
        return addPermissions(Arrays.asList(permissions));
    }

    public GYPermissionUtils setPermissions(List<String> permissionList) {
        this.permissionList.clear();
        return addPermissions(permissionList);
    }

    public GYPermissionUtils setPermissions(String... permissions) {
        return setPermissions(Arrays.asList(permissions));
    }

    public GYPermissionUtils setRequestCode(int requestCode) {
        this.requestCode = requestCode;
        return this;
    }

    public GYPermissionUtils setPermissionResult(PermissionResult permissionResult) {
        this.permissionResult = permissionResult;
        return this;
    }

    public void build(Context context) {
        List<String> noList = new ArrayList<>();
        //判断哪些权限未授予
        for (String permission : permissionList) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                noList.add(permission);
            }
        }
        if (!noList.isEmpty()) {
            String[] permissions = noList.toArray(new String[noList.size()]);
            ActivityCompat.requestPermissions(GYUtils.scanForActivity(context), permissions, requestCode);
        }
    }

    /**
     * 是否授权了权限
     *
     * @param context
     * @param permission
     * @return
     */
    public static boolean isAuthorized(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }
}
